package com.yd.mvc.mobile.userController;

import com.yd.app.service.mobile.userService.MUserService;
import com.yd.app.util.BusinessException;
import com.yd.domain.sys.User;
import com.yd.mvc.baseController.util.AuthUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.UUID;


@Controller
public class MLoginController {

	// 远程调用 @Reference()、本地调用@Autowired

	@Autowired
	MUserService mUserService;

	//管理员登录
	@ResponseBody
	@RequestMapping(value = "/dapi/m_user/login/{username}/{password}", method = RequestMethod.GET)
	public User adminLogin(@PathVariable("username") String username,@PathVariable("password") String password,HttpServletRequest request, HttpServletResponse response) throws Exception {

		User u = mUserService.login(username.toLowerCase(), password.trim());
		if (u == null){
			throw new BusinessException(500, "登录失败", "error_login");
		}else if(u.getCheckStatus().equals("0")){
			throw new BusinessException(500, "当前账号还未审核", "error_login");
		}else if(u.getCheckStatus().equals("2")){
			throw new BusinessException(500, "您的账号审核未通过", "error_login");
		}
		HttpSession session = request.getSession();
		session.setAttribute("login_user",u);

		//Cookie c = AuthUtil.login(response, u.getId(),u.getUserName(),"1");
		return u;
	}

	@RequestMapping("/dapi/m_user/logout")
	public String logout(HttpServletRequest request, HttpServletResponse response){
		AuthUtil.AuthedUser user = AuthUtil.getCurrentUser();
		Cookie cookie = new Cookie(AuthUtil.getCookieName(), String.format("0%s", UUID.randomUUID().toString()));
		cookie.setPath(AuthUtil.getCookiePath());
		//cookie.setDomain(AuthUtil.getCookieDomain());
		cookie.setMaxAge((int) AuthUtil.getExpierinterval()/1000);
		response.reset();
		response.addCookie(cookie);
		Date date = new Date();
		return "redirect:/";
	}

}
